package com.example.ilvuuz.interceptor;

import com.example.ilvuuz.common.Result;
import com.example.ilvuuz.utils.JwtUtil;
import com.example.ilvuuz.utils.ThreadLocalUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

@Component
public class JwtInterceptor implements HandlerInterceptor {
    @Autowired
    private JwtUtil jwtUtil;
    
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("Authorization");
        
        if (token == null || token.isEmpty()) {
            responseError(response, "未登录");
            return false;
        }
        
        Claims claims = jwtUtil.getClaimsByToken(token);
        if (claims == null || jwtUtil.isTokenExpired(claims)) {
            responseError(response, "token已过期");
            return false;
        }
        
        // 将用户信息存入ThreadLocal
        ThreadLocalUtil.set(claims.getSubject());
        return true;
    }
    
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 清理ThreadLocal
        ThreadLocalUtil.remove();
    }
    
    private void responseError(HttpServletResponse response, String message) throws Exception {
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().write(new ObjectMapper().writeValueAsString(Result.error(message)));
    }
} 